package com.gxsyh.nantie.excel.management.provider.service.impl;

import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.excel.management.provider.controller.dto.UploadData;
import com.gxsyh.nantie.excel.management.provider.domain.TbDepartmentUser;
import com.gxsyh.nantie.excel.management.provider.domain.TbUser;
import com.gxsyh.nantie.excel.management.provider.mapper.TbUserMapper;
import com.gxsyh.nantie.excel.management.provider.mapper.UploadMapper;
import com.gxsyh.nantie.excel.management.provider.service.UploadDataService;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author hua96
 * @Date 2020-02-19
 * @Time 14:44
 * @Version 1.0.0
 */
@Service
public class UploadDataServiceImpl implements UploadDataService {
    @Resource
    UploadMapper uploadMapper;
    @Resource
    TbUserMapper tbUserMapper;
    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUserList(List<UploadData> list) throws IOException {
        List<TbUser> listUser = new ArrayList<>();
        List<TbDepartmentUser> listDU = new ArrayList<>();
        TbUser tbUser = null;
        TbDepartmentUser tbDepartmentUser = null;
        String resultId = OkHttpClientUtil.getInstance().getData(LEAF_URL + "insertUser").body().string();

        for (int i = 0; i < list.size(); i++) {
            tbUser =new TbUser();
            tbDepartmentUser = new TbDepartmentUser();
            tbUser.setId(Long.valueOf(resultId));
            tbUser.setUsername(list.get(i).getUsername());
            tbUser.setJobNumber(list.get(i).getJobNumber());
            tbUser.setName(list.get(i).getName());
            tbUser.setPassword(bCryptPasswordEncoder.encode(list.get(i).getPassword()));
            tbUser.setSubsidyStatus(list.get(i).getSubsidyStatus());
            tbUser.setUserStatus(1);
            tbUser.setPhone(list.get(i).getPhone());
            tbUser.setCreated(new Date());
            tbUser.setUpdated(new Date());

            listUser.add(tbUser);

            if (list.get(i).getDepartmentId() == null){
                tbDepartmentUser.setDepartmentId(88L);
            }else {
                tbDepartmentUser.setDepartmentId(Long.valueOf(list.get(i).getDepartmentId()));
            }
            tbDepartmentUser.setUserId(listUser.get(i).getId());

            listDU.add(tbDepartmentUser);


        }
        uploadMapper.insertUserList(listUser);

        tbUserMapper.insertDU(listDU);
    }
}
